import Vue from "vue"
import VueRouter from 'vue-router'
import VueResource from 'vue-resource'
import { sync } from 'vuex-router-sync'
import * as myss from './demos/mystores.js'
import 'libs/jquery-1.11.3.min.js'
// import Echarts from 'vue-echarts'
// import ECharts from 'vue2-echarts'
import sha1 from 'js-sha1'
Vue.use(VueRouter)
// Vue.use(VueResource)
import App from './App'
import Vuex from 'vuex'
Vue.use(Vuex)
Vue.use(myss)
import vuexI18n from 'vuex-i18n'

require('es6-promise').polyfill()

/**
* you can add your module here
*/

let store = new Vuex.Store({
    modules: {
        i18n: vuexI18n.store
    }
})
var  myrest = "";
store.registerModule('vuxx', {
    state: {
        aabbccdd:334422,
        bbccssdd:344442114445556666,
        count:1,
        url:"http://116.228.152.190:666/lejf-mobile-api"
      },
    getters: {
        evenOrOddcc: state => state.count % 2 === 0  ?  'event' : 'odd'
    }
})
var environment = 'local';
var address = {
    local: {
        //获取token
        //getAccessTokenUrl:"http://appjk.lep365.com/get-access-token?mobileType=6&mobileId=h5",
        //getAccessTokenUrl:"http://10.8.8.16:8080/lejf-mobile-api/get-access-token?mobileType=6&mobileId=h5",
        //请求服务,
        baseapi:"http://appjk.lep365.com/api",
        //baseapi:"http://10.8.8.16:8080/lejf-mobile-api/api",
        //baseapi:"http://10.8.8.16:8080/lejf-mobile-api/api",
        duodata:"http://10.8.8.38:8081/lejf-game-api/api",
        //duodata:"http://xyx.lep365.com/lejf-game-api/api",
        //duopay:"http://10.8.8.13:8080/lejf-pay-api/api",
        duopay:"http://pay.lep365.com/lejf-pay-api/api",
        hgshop:"http://10.8.8.16:8080/lejf-mobile-api/hgShop/goods?accessToken=会话令牌"
    },
  public:{
        baseurl:"http://appjk.lep365.com/api",
        baseapi:"http://appjk.lep365.com/api",
        //baseapi:"http://appjk.lep365.com/lejf-mobile-api/api",
        //duodata:"http://10.8.8.38:8081/lejf-game-api/api",
        duodata:"http://xyx.lep365.com/lejf-game-api/api",
        //duopay:"http://10.8.8.13:8080/lejf-pay-api/api",
        duopay:"http://pay.lep365.com/lejf-pay-api/api",
        hgshop:"http://appjk.lep365.com/lejf-mobile-api/hgShop/goods?accessToken=会话令牌"
  },
  resultCode: {
    /** * 成功 */ SUCCESS: 0,
    /** * 无效的会话令牌 */ ACCESS_TOKEN_CHECK_FAIL: -1,
    /** * 签名认证失败 */ SIGN_CHECK_FAIL: -2,
    /** * 未登录 */ NO_LOGIN: -3,
    /** * 业务处理异常 */ HANDLING_ERROR: -4,
    /** * 未知系统异常 */ UNKNOW_ERROR: -5,
    /** * 未找到服务 */ NOTFOUND_SERVICE: -6,
    /** * 支付密码错误 */ TRADE_PWD_WRONG: -1001,
    /** * 短信验证码错误 */ VALID_CODE_WRONG: -1002,
    /** * 短信发送次数过多 */ SM_SEND_COUNT_TOO_MUCH: -1003
  }
}
var ggetter = {

}
var config = {
  environment: environment,
  service: address[environment]
}
Vue.use(config)
console.log(config.service.index)
var myrealrest = "";
store.registerModule('vux', {
  state: {
    iframeurl: '',
    mydir:'',
    iheight: '',
    myrest: {},
        agent:{
            'dls01':'93JD91',
            'dls02':'S3NSMS',
        },
        islogined:'false',
        placeholder:'',
      login: {
        accessToken:'',
        actionName:'',
        payload:'',
        sign:'',
        timestamp:'',
        secretKey:''
      },
        demoScrollTop: 0,
        isLoading: false,
        direction: 'forward',
        emulatedeal:'http://116.228.152.190:666/lejf-mobile-exchange-hq-api/api',
        tokenurl:'http://appjk.lep365.com/get-access-token?mobileType=6&mobileId=h5',
        tokeninurl:'http://10.8.8.16:8080/lejf-mobile-api/get-access-token?mobileType=6&mobileId=h5',
        directioddn: 'forwrsard',
        count:1,
        nots: [],
        requireCondition:{},
        authenticated:false,
        // rest_Login:false,
        rest_QueryHome:"",
        rest_SendValidCodeSM:"",
        rest_Login:"",
        rest_QueryUserInfo:"",
        single_QueryKnowledgeGroup:"",
        rest_QueryKnowledgeGroup:"",
        //single_QueryKnowledgeGroup:"",
        rest_QueryKnowledgeTag:"",
        rest_IndexProducts:"",
        rest_BuyProduct:"",
        rest_UserBuyedHistory:"",
        rest_2Login:"",
        rest_ShowWinRecord:"",
        rest_QueryUserInfo:"",
        rest_ProductDetail:"",
        rest_ProductParticipate:"",
        rest_ProductMore:"",
        rest_RandomNumberUser:"",
        rest_ProductImg:"",
        rest_ShareList:"",
        rest_ShareByUser:"",
        rest_UploadShare:"",
        rest_LuckyRecord:"",
        rest_ShareInfoShow:"",
        rest_PastPublish:"",
        rest_ShareByProduct:"",
        rest_CreateKnowledgeGroupOrder:'', //创建课程组订单
        //rest_CreateKnowledgeGroupOrder:'',
        single_CreateKnowledgeGroupOrder:'',
        rest_QueryKnowledgeTestAnswerDetail:'', // 查询已学课程详情
        rest_QueryKnowledgeGroupClassify:'',//查询课程分类
        rest_QueryKnowledgeGroupOrder:'', //查询课程组订单
        rest_UpdateGroupStudyRecord:'',//更新课程组学习记录
        rest_QueryGroupStudyRecord:'',//查询课程组学习记录
        rest_RecommendKnowledgeGroup:'',//课程组推荐
        rest_QuerySchoolContentGroupCollect:'', //查询课程组收藏
        rest_QueryHaveBoughtKnowledgeGroup:'',//查询已购课程组
        rest_555:'',
        rest_444:'',
        rest_333:'',
    },
    getters: {

      all_restful_333(state){
        return  state.rest_333
      },
      all_restful_444(state){
        return  state.rest_444
      },
      all_restful_555(state){
        return  state.rest_555
      },
      all_restful_QueryHaveBoughtKnowledgeGroup(state){
        return  state.rest_QueryHaveBoughtKnowledgeGroup //查询已购课程组
      },
      all_restful_QuerySchoolContentGroupCollect(state){
        return  state.rest_QuerySchoolContentGroupCollect
      },
      all_restful_RecommendKnowledgeGroup(state){
        return  state.rest_RecommendKnowledgeGroup //查询课程组收藏
      },
      all_restful_QueryGroupStudyRecord(state){
        return  state.rest_QueryGroupStudyRecord //查询课程组学习记录
      },
      all_restful_UpdateGroupStudyRecord(state){
        return  state.rest_UpdateGroupStudyRecord
      },
      all_restful_QueryKnowledgeGroupOrder(state){
        return  state.rest_QueryKnowledgeGroupOrder //查询课程组订单
      },
      all_restful_QueryKnowledgeGroupClassify(state){
        return  state.rest_QueryKnowledgeGroupClassify
      },
      all_restful_QueryKnowledgeTestAnswerDetail(state){
        return  state.rest_QueryKnowledgeTestAnswerDetail //查询已学课程详情
      },
      all_restful_Login(state){
        return  state.rest_2Login
      },
        evenOrOdd: state => state.count % 2 === 0  ?  'event' : 'odd',
      all_islogoined(state){
        return state.islogined
      },
      all_iheight(state){
        return state.iheight
      },
      all_iframeurl(state){
        return state.iframeurl
      },

       all_SendValidCodeSM(state){
         if(state.rest_SendValidCodeSM){

           return state.rest_SendValidCodeSM
         }
       },

      all_nlabel(state){
        if(state.rest_QueryKnowledgeTag){
          return state.rest_QueryKnowledgeTag
        }
      },
      all_singlegroup(state){
        return state.single_QueryKnowledgeGroup
      },
      all_restful_QueryKnowledgeGroup(state){
        return  state.rest_QueryKnowledgeGroup
        //return  state.single_QueryKnowledgeGroup
      },
       all_queryuserinfo(state){
         if(state.rest_QueryUserInfo){

               return state.rest_QueryUserInfo
             }
         },
        all_nots(state){
             return state.requireCondition
             // return state.nots
        },
        all_login(state){
            return state.login
        },
        all_agent(state){
            return state.agent
        },
        all_restful(state){
       //
            return  state.rest_Login
        },
        all_logindata(state){
          return  state.rest_Login
        },
        all_restful_QueryHome(state){
            return  state.rest_QueryHome
        },
        all_restful_IndexProducts(state){
            return  state.rest_IndexProducts
        },
        all_restful_BuyProduct(state){
            return  state.rest_BuyProduct
        },
        all_restful_UserBuyedHistory(state){
            return  state.rest_UserBuyedHistory
        },
        all_restful_ShowWinRecord(state){
            return  state.rest_ShowWinRecord
        },
        all_restful_QueryUserInfo(state){
            return  state.rest_QueryUserInfo
        },
        //夺宝预览页
        all_restful_ProductDetail(state){
            //alert("main:getters:all_restful_ProductDetail::"+state.rest_ProductDetail)
            return  state.rest_ProductDetail
        },
        //本品本期所有参与记录
        all_restful_ProductParticipate(state){
            return  state.rest_ProductParticipate
        },
        //夺宝码展示
        all_restful_RandomNumberUser(state){
            return  state.rest_RandomNumberUser
        },
        //图文详情 ProductImg
        all_restful_ProductMore(state){
            return  state.rest_ProductMore
        },
        //轮播图
        all_restful_ProductImg(state){
            return  state.rest_ProductImg
        },
        //所有晒单
        all_restful_ShareList(state){
            return  state.rest_ShareList
        },
        //所有晒单
        all_restful_ShareByUser(state){
            return  state.rest_ShareByUser
        },
        //我要晒单  LuckyRecord
        all_restful_UploadShare(state){
            return  state.rest_UploadShare
        },
        //幸运记录  LuckyRecord
        all_restful_LuckyRecord(state){
            return  state.rest_LuckyRecord
        },
        //晒单详情  ShareInfoShow
        all_restful_ShareInfoShow(state){
            return  state.rest_ShareInfoShow
        },
        //往期揭晓  PastPublish
        all_restful_PastPublish(state){
          return  state.rest_PastPublish
        },
        //往期晒单  ShareByProduct
        all_restful_ShareByProduct(state){
            return  state.rest_ShareByProduct
        },
        all_restful_CreateKnowledgeGroupOrder(state){
            return  state.rest_CreateKnowledgeGroupOrder //创建课程组订单
        },
        // all_restful_CreateKnowledgeGroupOrder(state){
        //     return  state.rest_CreateKnowledgeGroupOrder
        // },

    },
  mutations: {
      is_logined(state){
        state.islogined = true
      },

      height_iframe (state,height){
        state.iheight = height
      },
      login_iframe (state,url){
        state.iframeurl = url
      },
      login_accessToken (state,accessToken){
          state.login.accessToken = accessToken;
      },
      login_actionName (state,actionName){
          state.login.actionName = actionName;
      },
      login_secretKey (state,secretKey){
          state.login.secretKey = secretKey;
      },
      login_sign (state,sigin){
          state.login.sign = sigin;
      },
      login_timestamp (state,timestamp){
          state.login.timestamp = timestamp;
      },
      get_condition (state,token){
        state.requireCondition = token
      },
      add_nots(state,not) {
        state.nots.push(not)
      },
      updateDemoPosition (state, payload) {
        state.demoScrollTop = payload.top
      },
      updateLoadingStatus (state, payload) {
        state.isLoading = payload.isLoading
      },
      updateDirection (state, payload) {
        state.direction = payload.direction
      },
    initToken(state){
    },
    restful_api (state,payload){

        this.$http.get("http://10.8.8.16:8080/lejf-mobile-api/get-access-token?mobileType=6&mobileId=h5").then( (notes) => {
    // this.$http.get("http://appjk.lep365.com/get-access-token?mobileType=6&mobileId=h5").then( (notes) => {
          console.info("ls-secert",notes.body.accessToken)
          window.localStorage.setItem("ls-token",notes.body.accessToken)
          console.info("ls-token",notes.body.secretKey)
          window.localStorage.setItem("ls-secert",notes.body.secretKey)
        })
      // var mds = JSON.stringify(state.login)
      // console.info(mds);
       // state.login = {}
      // var  tm = new Date().getTime();
       var xxx = window.localStorage.getItem('saveuser')
       if(xxx)
      {
        state.login = xxx;
///1111111111111111111111111111111111111
            // state.islogined= true
      }
      else {

        state.login.secretKey = window.localStorage.getItem("ls-secert") ;
        state.login.actionName = payload.actionName;
        state.login.accessToken = window.localStorage.getItem("ls-token");
        // var xdd = ii.indexOf('knowledgeGroupId')
        // console.info(xdd,887);
      }
      var ii = JSON.stringify(payload.postData) // here should motiffy
      state.login.payload = ii;
      state.login.timestamp = new Date().getTime();
      state.login.sign =  sha1(state.login.accessToken + payload.actionName+ JSON.stringify(payload.postData) + state.login.timestamp  +state.login.secretKey );
      //   http.post(config.service[payload.url],state.login).then( (back)=> {
      //     myrest  = 'rest_'+ state.login.actionName;
      //     if(ii.indexOf('knowledgeGroupId') > -1){
      //     myrest  = 'single_'+ state.login.actionName;
      //       alert(myrest ,"查询或购买的单独某一个")
      //     }
      //     state[myrest] = back;
      //     if (payload.actionName == "Login"  && back.body.message =="登录成功") {
      //     window.localStorage.setItem("savelogin",back)
      //     window.localStorage.setItem("saveuser",state.login)
      //       state.islogined= true
      //     }
      // else {
      //   state.login.secretKey = window.localStorage.getItem("ls-secert") ;
      //   state.login.accessToken = window.localStorage.getItem("ls-token");
      //   state.login.sign =  sha1(state.login.accessToken + payload.actionName+ JSON.stringify(payload.postData) + state.login.timestamp  +state.login.secretKey );
      //   var ii = JSON.stringify(payload.postData) ;// here should motiffy
      //   state.login.actionName = payload.actionName;
      //   state.login.payload = ii;
      //   var xdd = ii.indexOf('knowledgeGroupId');
      //   console.info(xdd,887);
      // }
        http.post(config.service[payload.url],state.login).then( (back)=> {
          myrest  = 'rest_'+ state.login.actionName;
        var ii = JSON.stringify(payload.postData) ;// here should motiffy
          if(ii.indexOf('knowledgeGroupId') > -1){
          myrest  = 'single_'+ state.login.actionName;
            alert(myrest ,"查询或购买的单独某一个")
          }
          //console.info(myrest,"这里是你的接口变量");
          state[myrest] = back;
          //console.info(state[myrest],7777777777);
          if (payload.actionName == "Login"  && back.body.message =="登录成功") {
            // const history = window.sessionStorage
             // Event.fire("loginedd",back)

          window.localStorage.setItem("savelogin",back)
            var sl = JSON.stringify(state.login)
          window.localStorage.setItem("saveuser",sl)
            state.islogined= true
            //router.push('/Help')
              // router.push(state.mydir)
            router.push('/KeClassifyList')
            }

              // router.push("/profile")
            // }
            // router.push('/OneIndex')
          // }
          if (payload.postData.step!==undefined && payload.postData.step == 1) {
            alert(111111)
             Event.fire("gochecking",back)
          }
          else if (payload.actionName == "QueryUserInfo" )         {
            console.info(back.body.resultCode);
          // $vux.alert.show({
          //   title:'sssA',
          //   content:"asssskk"
          // })
            if (back.body.resultCode ==-3) {

              router.push('/login')
            }
         }
          // console.log(state.myrest,44444444444444444444)
          console.info(back);
        })

  },
  actions: {
      updateDemoPosition ({commit}, top) {
        commit({type: 'updateDemoPosition', top: top})
      },
      increment: ({ commit  }) => commit('increment'),
      decrement: ( { commit  }) => commit('decrement'),
      incrementIfOdd: ({commit,state}) =>{
          if ((state.count + 1) % 2 === 0){
            commit('increment');
            //alert("333333333")
          }
      }
  }
  }
})

Vue.use(vuexI18n.plugin, store)

// plugins
import { LocalePlugin, DevicePlugin, ToastPlugin, AlertPlugin, ConfirmPlugin, LoadingPlugin, WechatPlugin, AjaxPlugin, AppPlugin } from 'vux'
Vue.use(DevicePlugin)
Vue.use(ToastPlugin)
Vue.use(AlertPlugin)
Vue.use(ConfirmPlugin)
Vue.use(LoadingPlugin)
Vue.use(WechatPlugin)
Vue.use(AjaxPlugin)
Vue.use(LocalePlugin)
Vue.use(VueResource)
// Vue.use(Echarts )

// test
if (process.env.platform === 'app') {
  Vue.use(AppPlugin, store)
}

const wx = Vue.wechat
const http = Vue.http

/**
* -------------------------- 微信分享 ----------------------
* 请不要直接复制下面代码
*/

if (process.env.NODE_ENV === 'production') {
    wx.ready(() => {
        console.log('wechat ready')
        let postData = {
          "orderId":orderNo,
          "name":"knowledge",
          "catCode":"1",
          "device":"3",
          "payType":"3",
          "amount":totalPrice,
          "openid":openId,
        }
        this.$http.get('http://10.8.8.13:8080/lejf-pay-api',postData).then((data) => {
           console.log(data)
        })
        wx.onMenuShareAppMessage({
            title: 'VUX', // 分享标题
            desc: '基于 WeUI 和 Vue 的移动端 UI 组件库',
            link: 'https://vux.li?x-page=wechat_share_message',
            imgUrl: 'https://static.vux.li/logo_520.png'
        })

        wx.onMenuShareTimeline({
            title: 'VUX', // 分享标题
            desc: '基于 WeUI 和 Vue 的移动端 UI 组件库',
            link: 'https://vux.li?x-page=wechat_share_timeline',
            imgUrl: 'https://static.vux.li/logo_520.png'
        })
    })

    const permissions = JSON.stringify(['onMenuShareTimeline', 'onMenuShareAppMessage'])
    const url = document.location.href
    http.post('https://vux.li/jssdk?url=' + encodeURIComponent(url.split('#')[0]) + '&jsApiList=' + permissions).then(res => {
      wx.config(res.data.data)
    })
}

import objectAssign from 'object-assign'

const vuxLocales = require('json-loader!yaml-loader!vux/src/locales/all.yml')
const componentsLocales = require('json-loader!yaml-loader!src/locales/components.yml')
const globalLocales = require('json-loader!yaml-loader!src/locales/global_locales.yml') || {en: {}, 'zh-CN': {}}

const finalLocales = {
  'en': objectAssign(vuxLocales['en'], componentsLocales['en'], globalLocales['en']),
  'zh-CN': objectAssign(vuxLocales['zh-CN'], componentsLocales['zh-CN'], globalLocales['zh-CN'])
}

for (let i in finalLocales) {
    Vue.i18n.add(i, finalLocales[i])
}

const nowLocale = Vue.locale.get()
if (/zh/.test(nowLocale)) {
    Vue.i18n.set('zh-CN')
} else {
    Vue.i18n.set('en')
}

const FastClick = require('fastclick')
FastClick.attach(document.body)

// The following line will be replaced with by vux-loader with routes in ./demo_list.json
const routes = []
const router = new VueRouter({
  routes
})

sync(store, router)

// simple history management
const history = window.sessionStorage
history.clear()
let historyCount = history.getItem('count') * 1 || 0
history.setItem('/', 0)
let mypath = ""
router.beforeEach(function (to, from, next) {
  store.commit('updateLoadingStatus', {isLoading: true})
  // let mypath // = ""

  if(to.fullPath=="/login" && from.fullPath.indexOf("Details") > 0){
    mypath = "/OneIndex"
    Event.fire("baopath",from.fullPath)
    alert(mypath)
  }
  if(to.fullPath=="/login" && from.fullPath =="/trade"){
    mypath = "/trade"
    Event.fire("tradepath",mypath)

    alert(mypath)
  }
  var gopath = function(){
    router.push(mypath)
  }
// Event.listen("loginedd",()=>{
//   alert('truelove')
//   gopath()
// })
  const toIndex = history.getItem(to.path)
  const fromIndex = history.getItem(from.path)

  if (toIndex) {
    if (!fromIndex || parseInt(toIndex, 10) > parseInt(fromIndex, 10) || (toIndex === '0' && fromIndex === '0')) {
      store.commit('updateDirection', {direction: 'forward'})
    } else {
      store.commit('updateDirection', {direction: 'reverse'})
    }
  } else {
    ++historyCount
    history.setItem('count', historyCount)
    to.path !== '/' && history.setItem(to.path, historyCount)
    store.commit('updateDirection', {direction: 'forward'})
  }

  if (/\/http/.test(to.path)) {
    let url = to.path.split('http')[1]
    window.location.href = `http${url}`
  } else {
    next()
  }
})


router.afterEach(function (to) {
    store.commit('updateLoadingStatus', {isLoading: false})
    if (process.env.NODE_ENV === 'production') {
        ga && ga('set', 'page', to.fullPath)
        ga && ga('send', 'pageview')
    }
})

new Vue({
    store,
    router,
    myss,
    config,
    render: h => h(App)
}).$mount('#app')
window.Event = new class {
    constructor(){
        this.vue = new Vue();
      this.config = config
    }
    fire(event,data = null){
        this.vue.$emit(event,data);
    }
    listen(event,callback){
        this.vue.$on(event,callback);
    }
}
var goredir = function(e) {
  store.state.vux.mydir = e
}
             Event.listen("baopath",(e)=>{
goredir(e)
               // alert("hhahaha bao")
             })
             Event.listen("tradepath",(e)=>{

goredir(e)
               // alert("hhahaha trade")
             })
// alert = function() {};
console.log = function(){}
var islogineds= window.localStorage.getItem('saveuser')
if (islogineds) {
// store.state.vux.login = islogineds

}
